<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox v-model="layerVisibility.building"
                @change="toggleLayerVisibility('building')">建筑物</el-checkbox>
              <el-checkbox v-model="layerVisibility.facilities"
                @change="toggleLayerVisibility('facilities')">设施</el-checkbox>
              <el-checkbox v-model="layerVisibility.roads" @change="toggleLayerVisibility('roads')">道路</el-checkbox>
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="设施搜索" name="facilitySearch">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-input v-model="facilitySearchText" placeholder="请输入设施名称关键词" clearable>
                <template #append>
                  <el-button @click="searchFacilityByName">
                    <el-icon>
                      <Search />
                    </el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 建筑物属性查看对话框 -->
    <el-dialog v-model="buildingInfoVisible" title="建筑物信息" width="500px">
      <div v-if="selectedBuilding">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="建筑名称">{{
            selectedBuilding.attributes.name
          }}</el-descriptions-item>
          <el-descriptions-item label="建筑类型">{{
            selectedBuilding.attributes.Buildingtype
          }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{
            selectedBuilding.attributes.description
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buildingInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设施属性查看对话框 -->
    <el-dialog v-model="facilityInfoVisible" title="设施信息" width="500px">
      <div v-if="selectedFacility">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设施名称">{{
            selectedFacility.attributes.name
          }}</el-descriptions-item>
          <el-descriptions-item label="设施类型">{{
            selectedFacility.attributes.FacilitiesType
          }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{
            selectedFacility.attributes.description
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="facilityInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 道路属性查看对话框 -->
    <el-dialog v-model="roadInfoVisible" title="道路信息" width="500px">
      <div v-if="selectedRoad">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="道路名称">{{
            selectedRoad.attributes.name
          }}</el-descriptions-item>
          <el-descriptions-item label="道路类型">{{
            selectedRoad.attributes.RoadType
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roadInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 搜索结果列表对话框 -->
    <el-dialog v-model="searchResultVisible" title="设施搜索结果" width="500px" :key="refreshFacilityKey">
      <div v-if="searchResults.length > 0">
        <!-- 使用简单的列表替代表格 -->
        <div class="facility-list">
          <div v-for="(item, index) in searchResults" :key="index" class="facility-item"
            @click="handleFacilityRowClick(item)">
            <div class="facility-info">
              <div class="facility-name">名称：{{ item.attributes.name || '未知' }}</div>
              <div class="facility-type">类型：{{ item.attributes.FacilitiesType || '未知' }}</div>
              <div class="facility-desc">描述：{{ item.attributes.description || '无描述' }}</div>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="未找到匹配的设施"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="searchResultVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

let view: MapView | null = null
let buildingLayer: FeatureLayer | null = null
let facilitiesLayer: FeatureLayer | null = null
let roadsLayer: FeatureLayer | null = null

// 图层URL
const buildingLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/0'
const facilitiesLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/1'
const roadsLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/2'

// 图层可见性控制
const layerVisibility = ref({
  building: true,
  facilities: true,
  roads: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'facilitySearch'])
const refreshFacilityKey = ref(0)

// 查询结果相关
const buildingInfoVisible = ref(false)
const facilityInfoVisible = ref(false)
const roadInfoVisible = ref(false)
const searchResultVisible = ref(false)
let selectedBuilding: Graphic | null = null
let selectedFacility: Graphic | null = null
let selectedRoad: Graphic | null = null

// 设施搜索相关
const facilitySearchText = ref('')
let searchResults: Graphic[] = []

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'building':
      if (buildingLayer) {
        buildingLayer.visible = Boolean(layerVisibility.value.building)
      }
      break
    case 'facilities':
      if (facilitiesLayer) {
        facilitiesLayer.visible = Boolean(layerVisibility.value.facilities)
      }
      break
    case 'roads':
      if (roadsLayer) {
        roadsLayer.visible = Boolean(layerVisibility.value.roads)
      }
      break
  }
}

// 搜索设施
const searchFacilityByName = () => {
  if (!facilitiesLayer) {
    ElMessage.warning('设施图层未加载')
    return
  }

  if (!facilitySearchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  // 创建查询对象
  const query = new Query()
  query.where = `name LIKE '%${facilitySearchText.value}%'`
  query.outFields = ['*']
  query.returnGeometry = true

  // 执行查询
  facilitiesLayer
    .queryFeatures(query)
    .then((results) => {
      nextTick(() => {
        refreshFacilityKey.value++
      })
      if (results.features && results.features.length > 0) {
        searchResults = results.features
        console.log('查询结果:', searchResults)
        searchResultVisible.value = true
      } else {
        searchResults = []
        searchResultVisible.value = true
        ElMessage.info('未找到匹配的设施')
      }
    })
    .catch((error) => {
      console.error('查询设施出错:', error)
      ElMessage.error('查询设施失败')
    })
}

// 处理搜索结果行点击
const handleFacilityRowClick = (row: Graphic) => {
  selectedFacility = row
  searchResultVisible.value = false
  facilityInfoVisible.value = true

  // 如果有地图视图，则定位到该设施
  if (view && row.geometry) {
    view.goTo({
      target: row.geometry,
      zoom: 18,
    })
  }
}



// 初始化地图
onMounted(() => {
  // 创建建筑物图层 - 使用填充样式
  buildingLayer = new FeatureLayer({
    url: buildingLayerUrl,
    outFields: ['*'],
    visible: layerVisibility.value.building,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [255, 165, 0, 0.6], // 橙色半透明
        outline: {
          color: [255, 140, 0, 1], // 深橙色边框
          width: 2
        }
      }
    } as any,
    popupTemplate: {
      title: '建筑物信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '建筑名称' },
            { fieldName: 'BuildingType', label: '建筑类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })

  // 创建设施图层 - 使用点样式
  facilitiesLayer = new FeatureLayer({
    url: facilitiesLayerUrl,
    outFields: ['*'],
    visible: layerVisibility.value.facilities,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [0, 150, 255, 0.8], // 蓝色
        size: 12,
        outline: {
          color: [0, 100, 200, 1], // 深蓝色边框
          width: 2
        },
        style: 'circle'
      }
    } as any,
    popupTemplate: {
      title: '设施信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '设施名称' },
            { fieldName: 'FacilityType', label: '设施类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })

  // 创建道路图层 - 使用线样式，根据道路类型设置不同颜色
  roadsLayer = new FeatureLayer({
    url: roadsLayerUrl,
    outFields: ['*'],
    visible: layerVisibility.value.roads,
    popupEnabled: false,
    renderer: {
      type: 'unique-value',
      field: 'RoadType',
      defaultSymbol: {
        type: 'simple-line',
        color: [128, 128, 128, 0.8], // 灰色默认
        width: 3
      },
      uniqueValueInfos: [
        {
          value: '主干道',
          symbol: {
            type: 'simple-line',
            color: [255, 0, 0, 0.9], // 红色
            width: 6
          }
        },
        {
          value: '次干道',
          symbol: {
            type: 'simple-line',
            color: [255, 165, 0, 0.8], // 橙色
            width: 4
          }
        },
        {
          value: '支路',
          symbol: {
            type: 'simple-line',
            color: [255, 255, 0, 0.8], // 黄色
            width: 3
          }
        },
        {
          value: '步行道',
          symbol: {
            type: 'simple-line',
            color: [0, 255, 0, 0.8], // 绿色
            width: 2,
            style: 'dash'
          }
        },
        {
          value: '自行车道',
          symbol: {
            type: 'simple-line',
            color: [0, 191, 255, 0.8], // 天蓝色
            width: 2,
            style: 'dot'
          }
        }
      ]
    } as any,
    popupTemplate: {
      title: '道路信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '道路名称' },
            { fieldName: 'RoadType', label: '道路类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })

  // 创建地图
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [buildingLayer, facilitiesLayer, roadsLayer],
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 16,
    center: [116.79344073176162, 36.53820494873281], // 默认坐标，可修改为学校坐标
  })

  // 添加点击事件监听
  view.on('click', async (event) => {
    // 获取点击位置的屏幕坐标
    const screenPoint = {
      x: event.x,
      y: event.y,
    }

    // 创建查询对象
    const query = view?.hitTest(screenPoint)
    const response = await query

    // 如果没有点击到要素，则返回
    if (!response!.results || response!.results.length === 0) {
      return
    }

    // 遍历结果，查找图层要素
    for (const result of response!.results) {
      if ((result as any).graphic && (result as any).graphic.layer) {
        const layer = (result as any).graphic?.layer
        const graphic = (result as any).graphic

        // 根据图层类型显示不同的信息
        if (layer === buildingLayer) {
          selectedBuilding = graphic
          buildingInfoVisible.value = true
          return
        } else if (layer === facilitiesLayer) {
          selectedFacility = graphic
          facilityInfoVisible.value = true
          return
        } else if (layer === roadsLayer) {
          selectedRoad = graphic
          roadInfoVisible.value = true
          return
        }
      }
    }
  })

})



// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }


})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
}

.facility-list,
.building-facilities-list {
  max-height: 400px;
  overflow-y: auto;
}

.facility-item,
.building-facility-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.facility-item:hover {
  background-color: #f5f7fa;
}

.facility-info,
.building-facility-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.facility-name,
.building-facility-name {
  font-weight: bold;
}

.chart-container {
  height: 300px;
  margin: 20px 0;
}
</style>
